#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_FormGeography, COOPGIS_FormAssembly, COOPGIS_FormPoleTreatment, COOPGIS_FormCircuitTrace, COOPGIS_FormVegetationManager
import COOPGIS_FormMap, COOPGIS_FormStaker, COOPGIS_FormCostEstimate, COOPGIS_FormCommandTracker, COOPGIS_FormManagementConsole
import COOPGIS_FormBoardDistrict, COOPGIS_FormJointUseEditor, COOPGIS_FormLandmarkEditor, COOPGIS_FormInventoryCollection, COOPGIS_FormRoadEditor, COOPGIS_FormGroundRodTest
import COOPGIS_FormMaintenance, COOPGIS_FormSubstation, COOPGIS_FormGeneral, COOPGIS_FormCIS
import COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildForm(request, ApplicationName, DefaultMap=None, Assemblies=None, SpecialBuildFormInfo=None, station=None, span=None, point=None): 
    if(ApplicationName==djangoproject.settings.COOPGISAssemblyEditorApplicationName):
        FormDictionary=COOPGIS_FormAssembly.BuildAssemblyForm(DefaultMap, station=station, span=span)
    elif(ApplicationName==djangoproject.settings.COOPGISPoleTreatmentApplicationName):
        FormDictionary=COOPGIS_FormPoleTreatment.BuildPoleTreatmentForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISPoleTreatmentApplicationName + 'Report'):
        FormDictionary=COOPGIS_FormPoleTreatment.BuildPoleTreatmentReportForm()
    elif(ApplicationName==djangoproject.settings.COOPGISCircuitAnalysisApplicationName):
        FormDictionary=COOPGIS_FormAssembly.BuildAssemblyForm(DefaultMap, Assemblies=Assemblies, station=station, span=span)
    elif(ApplicationName==djangoproject.settings.COOPGISVegetationManagerApplicationName + 'CreateEditJob'):
        FormDictionary=COOPGIS_FormVegetationManager.BuildVegetationManagerCreateEditJobForm()
    elif(ApplicationName==djangoproject.settings.COOPGISVegetationManagerApplicationName + 'WorkJob'):
        FormDictionary=COOPGIS_FormVegetationManager.BuildVegetationManagerWorkJobForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISVegetationManagerApplicationName + 'Details'):
        FormDictionary=COOPGIS_FormVegetationManager.BuildVegetationManagerDetailsForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISStakerApplicationName):
        FormDictionary=COOPGIS_FormStaker.BuildStakerForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISStakerApplicationName + 'AssemblyEditor'):
        FormDictionary=COOPGIS_FormAssembly.BuildAssemblyForm(DefaultMap, station=station, span=span)
    elif(ApplicationName==djangoproject.settings.COOPGISMapSetupApplicationName):
        FormDictionary=COOPGIS_FormMap.BuildMapForm()
    elif(ApplicationName==djangoproject.settings.COOPGISMapSetupApplicationName + 'Template'):
        FormDictionary=COOPGIS_FormMap.BuildMapTemplateForm()
    elif(ApplicationName==djangoproject.settings.COOPGISViewerApplicationName):
        FormDictionary=COOPGIS_FormAssembly.BuildAssemblyForm(DefaultMap, Viewer=True)
    elif(ApplicationName==djangoproject.settings.COOPGISViewerApplicationName + 'Asset'):
        FormDictionary=COOPGIS_FormAssembly.BuildAssetViewerForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISCostEstimateApplicationName):
        FormDictionary=COOPGIS_FormCostEstimate.BuildCostEstimateForm()
    elif(ApplicationName==djangoproject.settings.COOPGISCostEstimateApplicationName + 'Contract'):
        FormDictionary=COOPGIS_FormCostEstimate.BuildCostEstimateContractForm()
    elif(ApplicationName==djangoproject.settings.COOPGISManagementConsoleApplicationName + 'CommandTracker'):
        FormDictionary=COOPGIS_FormCommandTracker.BuildCommandTrackerForm()
    elif(ApplicationName==djangoproject.settings.COOPGISManagementConsoleApplicationName):
        FormDictionary=COOPGIS_FormManagementConsole.BuildManagementConsoleForm()
    elif(ApplicationName==djangoproject.settings.COOPGISStakerApplicationName + 'QuickGenerate'):
        FormDictionary=COOPGIS_FormStaker.BuildStakerQuickGenerateForm(DefaultMap, Assemblies=Assemblies)
    elif(ApplicationName==djangoproject.settings.COOPGISBoardDistrictApplicationName):
        FormDictionary=COOPGIS_FormBoardDistrict.BuildBoardDistrictForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISJointUseEditorApplicationName):
        FormDictionary=COOPGIS_FormJointUseEditor.BuildJointUseEditorForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISInventoryCollectionApplicationName):
        FormDictionary=COOPGIS_FormInventoryCollection.BuildInventoryCollectionForm(DefaultMap,Shortcuts=SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISRoadEditorApplicationName):
        FormDictionary=COOPGIS_FormRoadEditor.BuildRoadEditorForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISConditionEditorApplicationName):
        FormDictionary=COOPGIS_FormMaintenance.BuildConditionEditorForm(DefaultMap, point)
    elif(ApplicationName==djangoproject.settings.COOPGISConditionDispatchApplicationName):
        FormDictionary, NumberOfConditionsListedOnDispatchForm=COOPGIS_FormMaintenance.BuildConditionDispatchForm(request)
    elif(ApplicationName==djangoproject.settings.COOPGISGPSTraceApplicationName):
        FormDictionary=COOPGIS_FormGeography.BuildGPSTraceForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'InspectionChoice'):
        FormDictionary=COOPGIS_FormSubstation.BuildInspectionChoiceForm()
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'EquipmentModelType'):
        FormDictionary=COOPGIS_FormSubstation.BuildEquipmentModelTypeForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationSetup'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationSetupForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISGeneralApplicationName + 'VoltageSetup'):
        FormDictionary=COOPGIS_FormGeneral.BuildVoltageSetupForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISGeneralApplicationName + 'CompanySetup'):
        FormDictionary=COOPGIS_FormGeneral.BuildCompanySetupForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationEquipmentTemplateSetup'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationEquipmentTemplateForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationEquipmentSetup'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationEquipmentForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationEquipmentTest'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationEquipmentTestForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationEquipmentSetting'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationEquipmentSettingForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationInspection'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationInspectionForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationEquipmentInspection'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationEquipmentInspectionForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISSubstationApplicationName + 'SubstationCircuit'):
        FormDictionary=COOPGIS_FormSubstation.BuildSubstationCircuitForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISWarehouseApplicationName + 'meterinventorycheckin'):
        FormDictionary=COOPGIS_FormSubstation.BuildWarehouseMeterInventoryCheckInForm()
    elif(ApplicationName==djangoproject.settings.COOPGISWarehouseApplicationName + 'meterinspectionchoice'):
        FormDictionary=COOPGIS_FormSubstation.BuildWarehouseMeterInspectionChoiceForm()
    elif(ApplicationName==djangoproject.settings.COOPGISCISRestrictedApplicationName + 'SSN'):
        FormDictionary=COOPGIS_FormCIS.BuildSSNSearchForm()
    elif(ApplicationName==djangoproject.settings.COOPGISGroundRodTestApplicationName):
        FormDictionary=COOPGIS_FormGroundRodTest.BuildGroundRodTestForm(DefaultMap)
    elif(ApplicationName==djangoproject.settings.COOPGISGroundRodTestApplicationName + 'Report'):
        FormDictionary=COOPGIS_FormGroundRodTest.BuildGroundRodTestReportForm()
    elif(ApplicationName==djangoproject.settings.COOPGISLandmarkEditorApplicationName + 'Point'):
        FormDictionary=COOPGIS_FormLandmarkEditor.BuildLandmarkPointEditorForm(DefaultMap, SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISLandmarkEditorApplicationName + 'Line'):
        FormDictionary=COOPGIS_FormLandmarkEditor.BuildLandmarkLineEditorForm(DefaultMap, SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISLandmarkEditorApplicationName + 'Polygon'):
        FormDictionary=COOPGIS_FormLandmarkEditor.BuildLandmarkPolygonEditorForm(DefaultMap, SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISOutdoorLightingApplicationName):
        FormDictionary=COOPGIS_FormMaintenance.BuildOutdoorLightingForm(DefaultMap, point)
    elif(ApplicationName==djangoproject.settings.COOPGISOutdoorLightingApplicationName + 'SendToBilling'):
        FormDictionary=COOPGIS_FormMaintenance.BuildOutdoorLightingSendToBillingForm(SpecialBuildFormInfo)
    elif(ApplicationName==djangoproject.settings.COOPGISGeneralApplicationName + 'CategorizeByCompatibleUnit'):
        FormDictionary=COOPGIS_FormGeneral.BuildCompatibleUnitCategorizationForm()
    else:
        raise(Exception('An Invalid Application Name was specified in BuildForm in COOPGIS_FormMisc.py'))
    if request.method == 'POST':  #Setup the form so it can be processed/modified on this postback
        form=COOPGIS_Misc.DynForm()
        form.setFields(FormDictionary)
        form.setData(request.POST)
        data={}
        for i in form.data.keys():  #Copy the Form Data to a dictionary then back to the form so it can be modified for the next screen view
            data[i] = form.data[i]
        form.data = data
    else:   #Otherwise, setup the Boolean values checked for processing to false
        form=COOPGIS_Misc.DynForm()
        form.setFields(FormDictionary)
        form.data={}
    if(ApplicationName==djangoproject.settings.COOPGISConditionDispatchApplicationName):
        return form, NumberOfConditionsListedOnDispatchForm
    else:
        return form

def PopulateMiscFormFields(form):
    form.data['RunDeleteURDMarkerStationIndicator'] = False #Make sure this is false on every postback to prevent accidental deletions
    form.data['GeoTraceConfirmChangeCircuit'] = ''  #Always reset on every postback to avoid unwanted changes
    form.data['GeoTraceConfirmChangeCompatibleUnit'] = ''  #Always reset on every postback to avoid unwanted changes
    form.data['GeoTraceConfirmChangePhase'] = '' #Always reset on every postback to avoid unwanted changes
    form.data['SplitSpanIndicator']=False #Do not ever save attempting to split a span on a postback to avoid unintentional splitting of spans
    form.data['DeleteStationIndicator']=False  #Never Delete a Station after a postback unless delete is reselected
    form.data['DeleteSpanIndicator']=False #Never Delete a Span after a postback unless delete is reselected
    form.data['StationTransformerBank'] = -1  #Always set StationAssemblyTransformerBank back to the None Selection to not create or delete anything at the current station
    try:
        form.data['PreviousStationid']=form.data['SelectStationid']
    except:
        form.data['PreviousStationid']=''
    try:
        form.data['PreviousSpanid']=form.data['SelectSpanid']
    except:
        form.data['PreviousSpanid']=''
    return form

def FormGetBoolean(form, FieldName):
    try:
        Result=bool(form.data[FieldName] == 'on')
    except:
        Result=False
    return Result

def FormGetFloat(form, FieldName, Default=0):
    try:
        String=form.data[FieldName]
    except:
        return Default
    String = String.replace(',', '')
    try:
        Result=float(String)
    except:
        Result=Default
    return Result

def FormGetInteger(form, FieldName, Default=0):
    try:
        return int(FormGetFloat(form, FieldName, Default))
    except:
        return Default

def FormGetString(form, FieldName, Default=''):
    try:
        Result=form.data[FieldName]
    except:
        Result=Default
    return Result

def FormGetDateTime(form, FieldName):
    String=FormGetString(form, FieldName)
    try:
        DateTime=COOPGIS_String.StringDateTimeToDateTime(String)
    except:
        return None
    #raise(Exception(str(DateTime)))
    return DateTime

def FormGetGeographicData(form, FieldName):
    try:
        return fromstr(form.data[FieldName])
    except:
        return None

def FormGetObjectFromid(form, FieldName, Object):
    Objectid=FormGetInteger(form, FieldName)
    if(id):
        Result=Object.objects.all().filter(id=Objectid)
    else:
        return None
    if(Result):
        return Result[0]
    else:
        return None

def FormGetGeometryFromWKT(form, FieldName):
    try:
        RawGeometryString=FormGetString(form, FieldName)
        MercatorGeometry = GEOSGeometry(RawGeometryString)
        #Mercator projection used in OpenLayers vector layer
        MercatorGeometry.srid=3857
        GISGeometry = MercatorGeometry.transform(djangoproject.settings.COOPGISSRID, clone=True)
        return GISGeometry
    except:
        return None
